<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\admin\service\EducationRequirementService;
use app\admin\service\EnterpriseService;
use app\admin\service\RecruitRejectService;
use app\admin\service\RecruitService;
use app\admin\service\SubscribeLogService;
use app\admin\service\UsersService;
use app\admin\service\WorkExperienceService;
use app\admin\validate\Recruit as RecruitValidate;
use app\AdminController;
use think\exception\ValidateException;

/**
 * 招聘管理
 * Class Recruit
 * @package app\admin\controller
 */
class Recruit extends AdminController
{
    /**
     * 招聘列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $where = [];
        if (request()->isPost()) {
            // 关键词搜索
            $keywords = trim($this->request->param('keywords', ''));
            if ($keywords) {
                $where[] = ['er.position|e.name|c.name', 'like', '%' . $keywords . '%'];
            }

            $where[] = ['er.status', '=', 1];
            $list = RecruitService::getRecruitList($where, $this->page, $this->pagesize);
            $count = RecruitService::countRecruitList($where);

            return adminResponseJson(['list' => $list, 'count' => $count]);
        }

        return view();
    }

    /**
     * 招聘发布
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recruitAdd()
    {
        if (request()->isPost()) {
            $data = request()->post();

            try {
                validate(RecruitValidate::class)->recruitInsert()->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $users = UsersService::findUsers(['id' => $data['uid']]);
            if (!$users) {
                $this->error(adminJsonMsg(10010));
            }

            // 最高低于最低薪资
            if ($data['max_salary'] < $data['min_salary']) {
                $this->error(adminJsonMsg(10025));
            }

            // 1 => 已通过
            $data['status'] = 1;

            RecruitService::createRecruit($data);

            $this->success(adminJsonMsg(1004), (STRING)url('/recruit/index'));
        }

        // 企业数据
        $list['enterprise'] = EnterpriseService::getEnterprise();
        // 学历要求
        $list['education'] = EducationRequirementService::getEducationRequirement();
        // 工作经验
        $list['work'] = WorkExperienceService::getWorkExperience();

        return view('', ['list' => $list]);
    }

    /**
     * 招聘编辑
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recruitEdit()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }

        if (request()->isPost()) {
            $data = request()->post();

            try {
                validate(RecruitValidate::class)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $users = UsersService::findUsers(['id' => $data['uid']]);
            if (!$users) {
                $this->error(adminJsonMsg(10010));
            }

            // 最高低于最低薪资
            if ($data['max_salary'] < $data['min_salary']) {
                $this->error(adminJsonMsg(10025));
            }

            RecruitService::updateRecruit($data, ['id' => $data['id']]);

            $this->success(adminJsonMsg(1004), (STRING)url('/recruit/index'));
        }

        $info = RecruitService::findRecruit(['id' => $id]);
        if (!$info) {
            $this->error(adminJsonMsg(1002));
        }

        // 企业数据
        $list['enterprise'] = EnterpriseService::getEnterprise();
        // 学历要求
        $list['education'] = EducationRequirementService::getEducationRequirement();
        // 工作经验
        $list['work'] = WorkExperienceService::getWorkExperience();

        return view('', ['info' => $info, 'list' => $list]);
    }

    /**
     * 招聘详情
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recruitShow()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }

        $info = RecruitService::findRecruit(['id' => $id], 1);

        return view('', ['info' => $info, 'source' => intval($this->request->param('source', 0))]);
    }

    /**
     * 修改状态
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changeStatus()
    {
        if (request()->isPost()) {

            $id = intval($this->request->param('id', 0));
            // 2=>删除  1=>通过  -1=>驳回
            $status = intval($this->request->param('status', 2));
            // 驳回原因
            $reason = $this->request->param('reject_reason', '');
            if (!$id) {
                $this->error(adminJsonMsg(1001));
            }

            $where = ['id' => $id];
            $info = RecruitService::findRecruit($where);
            if (!$info) {
                $this->error(adminJsonMsg(1002));
            }

            $update = ['status' => $status];
            RecruitService::updateRecruit($update, $where);

            if ($status == -1) {
                // 写入驳回记录表
                RecruitRejectService::createRecruitReject([
                    'recid' => $id,
                    'reason' => $reason,
                    'reject_time' => time(),
                ]);
            }

            // 通过/驳回，推送消息
            if (in_array($status, [1, -1])) {
                $map = [
                    // 关联表id
                    'relation_id' => $id,
                    'uid' => $info['uid'],
                    // 1企业  2社群  3招聘
                    'type' => 3,
                    'is_push' => 0
                ];
                SubscribeLogService::updateSubscribeLog($map, [
                    'status' => $status
                ]);
            }

            $this->success(adminJsonMsg(1004));
        }
    }
}